package com.hui.demo.listener;

import com.hui.demo.model.User;
import com.hui.demo.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * 监听器
 * @author ziv
 * @date 2018-12-15
 */
@WebListener
public class UserListener implements ServletContextListener {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    private static final String ALLUSER = "allUserList";

    /**
     * 使用log日志打印输出
     */
    Logger logger = LogManager.getLogger(this.getClass());

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // 查询数据库所有用户
        List<User> userList = userService.findAll();
        // 清除缓存中的用户数据
        redisTemplate.delete(ALLUSER);
        // 将数据存放到缓存中
        redisTemplate.opsForList().leftPushAll(ALLUSER, userList);
        // 查询所有用户数据（正式项目需删除）
        List<User> allUser = redisTemplate.opsForList().range(ALLUSER, 0, -1);
        logger.info("缓存中目前的用户数：" + allUser.size() + "人");
        logger.info("servletContent 上下文初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        logger.info("servletContent 上下文销毁");
    }
}